package edu.zhoujw.project.infra.config;

import cn.hutool.core.util.StrUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 国际化配置类
 *
 * @author Shawn
 * @since 2023/9/14 11:18:49
 */
@Configuration
public class I18nConfig implements WebMvcConfigurer {

    /**
     * 语言区域解析器, 用来设置当前会话国际化语言
     * @return 语言区域解析器
     */
    @Bean
    public LocaleResolver localeResolver() {
        return new LocaleResolver() {
            @NotNull
            @Override
            public Locale resolveLocale(@NotNull HttpServletRequest httpServletRequest) {
                // 从请求头获取语言编码
                String lang = httpServletRequest.getHeader("lang");
                if (StrUtil.isBlank(lang)) {
                    return Locale.getDefault();
                }

                // 统一格式
                lang = lang.replaceAll("-", "_");

                try {
                    String[] split = lang.split("_");
                    // 接收第一个参数为语言代码，第二个参数为国家代码
                    return new Locale(split[0], split[1]);
                } catch (Exception e) {
                    // 不识别的情况, 返回默认语言
                    return Locale.getDefault();
                }
            }

            @Override
            public void setLocale(@NotNull HttpServletRequest httpServletRequest,
                                  HttpServletResponse httpServletResponse,
                                  Locale locale) {

            }
        };
    }

}
